package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/21 13:25
 */
public class C23 {

    // 暴力解归并, 使用额外空间的链表
    public static ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0) return null;
        return process(lists, 0, lists.length-1);
    }

    // 不直接遍历数组合并了, 这回递归调用, 使要合并的链表尽量均等
    public static ListNode process(ListNode[] lists, int start, int end) {
        if(start == end) return lists[start];
        int m = (start + end) >> 1;
        ListNode left = process(lists, start, m);
        ListNode right = process(lists, m + 1, end);
        return merge(left, right);
    }

    public static ListNode merge(ListNode l1, ListNode l2) {
        ListNode help = new ListNode(-1);
        ListNode cur = help;
        while (l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 == null ? l2 : l1;
        return help.next;
    }

    // for test
    private static void printList(ListNode root) {
        if(root == null) return;
        ListNode cur = root;
        while (cur != null) {
            System.out.print(cur.val + "  ");
            cur = cur.next;
        }
        System.out.println();
    }

    // for test
    public static void main(String[] args) {
        ListNode[] lists = new ListNode[3];
        lists[0] = new ListNode(1);
        lists[0].next = new ListNode(4);
        lists[0].next.next = new ListNode(5);

        lists[1] = new ListNode(1);
        lists[1].next = new ListNode(3);
        lists[1].next.next = new ListNode(4);

        lists[2] = new ListNode(2);
        lists[2].next = new ListNode(6);


        ListNode newList = mergeKLists(lists);
        printList(newList);
    }


}
